<?php
/**
 * Created by IntelliJ IDEA.
 * User: FX
 * Date: 2018/1/27
 * Time: 16:34
 */
namespace common\service\sms;

use common\service\sms\ihuyi\sms;
use yii\web\NotFoundHttpException;

class Client
{

    const CACHE_TIME = 120;

    const CACHE_KEY = 'mobile:sms:key';


    public $mobile;

    /**
     * @var sms
     */
    public $client;
    /**
     * @param $type
     */
    public function __construct($type)
    {
        switch($type){
            case 'ihuyi':
                $this->client = new sms();
                break;
            default:
                break;
        }
    }

    /**
     * @param $mobile
     * @return $this
     * @throws NotFoundHttpException
     */
    public function setMobile($mobile)
    {
        if(!preg_match("/^1[34578]\d{9}$/", $mobile)){
            throw new NotFoundHttpException('手机号码格式有问题！');
        }
        $this->mobile = $mobile;
        return $this;
    }

    /**
     * @param string $type
     * @return Client
     */
    public static function getInstance($type='ihuyi')
    {
        return new self($type);
    }

    /**
     * @throws NotFoundHttpException
     */
    public function send()
    {
        if(\Yii::$app->cache->get(self::CACHE_KEY.$this->mobile)){
            throw new NotFoundHttpException(self::CACHE_TIME,200);
        }
        $rand = $this->random(4,1);
        if( $this->client->send($this->mobile,$rand) ){
            //将随机数 记录session 作比较
            \Yii::$app->cache->set(self::CACHE_KEY.$this->mobile,$rand,self::CACHE_TIME);
        }
    }

    /**
     * @param string $code
     * @return bool
     * @throws NotFoundHttpException
     */
    public function check($code='')
    {
        if( \Yii::$app->cache->get(self::CACHE_KEY.$this->mobile) == $code ){
            $this->clear();
            return true;
        }
        throw new NotFoundHttpException('手机验证码校验失败！');
    }

    /**
     * 清除code
     */
    public function clear()
    {
        \Yii::$app->cache->delete(self::CACHE_KEY.$this->mobile);
    }

    /**
     * random() 函数返回随机整数。
     * @param int $length
     * @param int $numeric
     * @return string
     */
    public function random($length = 6 , $numeric = 0) {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if($numeric) {
            $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }
}